<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\madmin\service;

use app\madmin\model\Advert;
use app\madmin\model\Commodity;
use app\madmin\model\LiveGood;
use app\madmin\model\LiveLog;
use app\madmin\model\LiveRoom;
use app\madmin\model\LiveRoomHasGood;
use app\madmin\model\Mytemplate;
use app\madmin\model\Renovation;
use app\madmin\model\Template;
use app\madmin\model\TemplateClassify;
use app\utils\LiveErrorCode;
use app\utils\LiveGoods;
use app\utils\Wechat;
use shopstar\components\wechat\helpers\MiniProgramBroadcastRoomHelper;
use shopstar\components\wechat\helpers\MiniProgramMediaHelper;
use shopstar\constants\broadcast\BroadcastLogConstant;
use shopstar\constants\broadcast\BroadcastRoomIsDeletedConstant;
use shopstar\helpers\FileHelper;
use shopstar\models\log\LogModel;
use shopstar\services\core\attachment\CoreAttachmentService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;

class LiveGoodService
{

    public function list()
    {

        $where=[];
        $data=request()->get();
        $page=\request()->get('page',1);
        $size=\request()->get('size',10);

        $query=LiveGood::with(["goods"]);
        if (!empty($data['name'])){
            $query->haswhere('goods',function($query) use ($data){
                $query->where('name','like',"%{$data['name']}%");
            });
        }
        !empty($data['status']) && $query->where('status','=',$data['status']);
        $result = $query->paginate(['page' => $page, 'list_rows' => $size]);
//        $offset = \request()->get('offset', 0);
//        $limit = \request()->get('limit', 30);
//        $status = \request()->get('status', 0);
//        $data = [
//            'offset' => $offset,
//            'limit' => $limit,
//            'status' => $status
//        ];
//        $result = LiveGoods::getApproved($data);
//        $err_msg = LiveErrorCode::getError($result);
//        if (!empty($err_msg)) {
//            return [HTTP_NOTACCEPT, $err_msg];
//        }
        return [HTTP_SUCCESS, $result];
    }

    /**
     * 添加审核
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function addAudit($id)
    {

        $commodity = Commodity::where(['id' => $id])->find();
        if (empty($commodity)) {
            return [HTTP_NOTACCEPT, '商品不存在'];
        }
        $liveGood = LiveGood::where(['goods_id' => $id])->find();
        if (!empty($liveGood)) {
            return [HTTP_NOTACCEPT, '商品已经在审核列表中'];
        }
        $param = ['width' => 300, 'height' => 300, 'fixed' => true];

        $thumbMedia=Wechat::uploadImage($commodity->master, $param);

        $err_msg = LiveErrorCode::getError($thumbMedia);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }
        $thumbMediaId = $thumbMedia['media_id'];

        $model = new LiveGood();
        setAttributes($model, [
            'goods_id' => $commodity->id,
            'cover_img_url' => $commodity->master,
            'cover_img_media_id' => $thumbMediaId,
            'status' => 0,
            'create_time' => date("Y-m-d H:i:s"),
            'mall_id' => $commodity->mall_id,
            'price'=>$commodity->sell_price,
            'price1'=>0,
            'price_type'=>1,
            'name'=> mb_substr($commodity->name, 0, 12) . (mb_strlen($commodity->name) > 12 ? '...' : '')
        ]);

        $result = LiveGoods::add([
            'coverImgUrl' => $thumbMediaId,
            'name' => mb_substr($commodity->name, 0, 12) . (mb_strlen($commodity->name) > 12 ? '...' : ''),
            'priceType' => 1,//$goods->has_option == 0 ? 1 : 2, //单规格1口价  多规格区间价
            'price' => $commodity->sell_price,
            'url' => "pages/detail/detail?id={$commodity->id}&mall_id=$commodity->mall_id"
//                'url' => 'pages/index/index?goods_id=' . $goods->id,
        ]);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        //赋值商品库商品id和审核id
        $model->room_goods_id = $result['goodsId'];
        $model->audit_id = $result['auditId'];

        $model->save();

        LiveLog::write(
            '添加审核商品',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '商品id' => $commodity->id,
                    '商品名称' => $commodity->name
                ]
            ]
        );
        return [HTTP_SUCCESS, $model];
    }

    public function updateGoods($id){
        $data=\request()->post();

        $model=LiveGood::where(['room_goods_id'=>$id])->find();
        if(empty($model)){
            throw new \Exception('商品获取不到');
        }
        if(!empty($data['cover_img_url'])){
            $param = ['width' => 300, 'height' => 300, 'fixed' => true];
            $thumbMediaId = Wechat::uploadImage($data['cover_img_url'], $param)['media_id'];
        }else{
            $thumbMediaId=$model->cover_img_media_id;
        }
        $data['cover_img_media_id']=$thumbMediaId;
        setAttributes($model,$data);
        $data=[
            'coverImgUrl'=>$thumbMediaId,
            'name'=>mb_substr($data['name'], 0, 12) . (mb_strlen($data['name']) > 12 ? '...' : ''),
            'priceType'=>$data['price_type'],
            'price'=>$data['price'],
            'price2'=>$data['price2'] ?? 0,
            'goodsId'=>$model->room_goods_id
        ];

        if($model->status==2){
            //当审核通过后只能更改价格字段
            unset($data['coverImgUrl']);
            unset($data['name']);

        }

        $result = LiveGoods::update($data);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }
        $model->save();
        return [HTTP_SUCCESS, "更新成功"];
    }

    /**
     * 撤销审核
     */
    public function resetAudit($broadcastGoodsId)
    {

        $data = [
            'goodsId' => $broadcastGoodsId,
            'auditId' => request()->post("audit_id", 0),
        ];
        $model = LiveGood::where(['room_goods_id' => $broadcastGoodsId])->find();

        if (empty($model)) {
            return [HTTP_NOTACCEPT, '找不到商品审核信息,请先发起添加商品审核'];
        }
        if ($model->status != 1) {
            return [HTTP_NOTACCEPT, '只有审核中,才可以进行撤销'];
        }
        $result = LiveGoods::resetAudit($data);

        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        //撤销删除商品库
        LiveGood::where(['room_goods_id' => $broadcastGoodsId])->delete();

        LiveLog::write(
            '撤销审核商品',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播商品id' => $model->id,
                    '商品id' => $model->goods_id,
                ]
            ]
        );
        return [HTTP_SUCCESS, "撤销成功"];
    }

    /**
     * 重新审核
     */
    public function repeatAudit($broadcastGoodsId)
    {
        $data = [
            'goodsId' => $broadcastGoodsId,
        ];
        $model = LiveGood::where(['room_goods_id' => $broadcastGoodsId])->find();
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '找不到商品审核信息,请先发起添加商品审核'];
        }
        if ($model->status == 3) {
            return [HTTP_NOTACCEPT, '只有审核驳回或拒绝,才可以进行重新审核'];
        }
        $result = LiveGoods::audit($data);
        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }
        //撤销删除商品库
        LiveGood::update(['status' => 0], [
            'room_goods_id' => $broadcastGoodsId,
        ]);
        LiveLog::write(
            '重新审核商品',
            [
                'log_data' => $model->getData(),
                'log_primary' => [
                    '直播商品id' => $model->id,
                    '商品id' => $model->goods_id,
                ]
            ]
        );
        return [HTTP_SUCCESS, "重新审核成功"];
    }

    /**
     * 删除商品审核
     */
    public function deleteAudit($broadcastGoodsId)
    {
        $data = [
            'goodsId' => $broadcastGoodsId,
        ];
        $model = LiveGood::where(['room_goods_id' => $broadcastGoodsId])->find();
//        if(empty($model)){
//            return [HTTP_NOTACCEPT, '找不到商品审核信息,请先发起添加商品审核'];
//        }

        $result = LiveGoods::delete($data);
        $err_msg = LiveErrorCode::getError($result);
        if (!empty($err_msg)) {
            return [HTTP_NOTACCEPT, $err_msg];
        }

        //删除商品映射
        LiveRoomHasGood::where(['room_goods_id' => $broadcastGoodsId])->delete();
        LiveGood::where(['room_goods_id' => $broadcastGoodsId])->delete();
        if (!empty($model)) {
            LiveLog::write(
                '删除审核商品',
                [
                    'log_data' => $model->getData(),
                    'log_primary' => [
                        '直播商品id' => $model->id,
                        '商品id' => $model->goods_id,
                    ]
                ]
            );
        }

        return [HTTP_SUCCESS, "删除审核成功"];
    }
}